// 此文件主要用于权限校验判断(token)
import router from '@/router'
import { getToken } from './utils/auth'
import { asnycRoutes } from '@/router/asyncRoutes'
import store from './store'
function getFirstRoutePerms(PermsArry) {
  const newArray = PermsArry.map(item => {
    return item.split(':')[0]
  })
  return [...new Set(newArray)]
}
function getSecondRoutePerms(PermsArry) {
  const newArray = PermsArry.map(item => {
    const res = item.split(':')
    return `${res[0]}:${res[1]}`
  })
  return [...new Set(newArray)]
}

function getRoutes(firstPerms, secondPerms, asnycRoutes) {
  if (firstPerms.includes('*')) {
    return asnycRoutes
  }
  return asnycRoutes.filter(route => {
    return firstPerms.includes(route.permission)
  }).map(item => {
    return {
      ...item,
      children: item.children.filter(item => {
        return secondPerms.includes(item.permission)
      })
    }
  })
}
// 白名单
const whiteList = ['/login', '/404']
// 路由导航守卫
router.beforeEach(async(to, from, next) => {
  // 先获取token
  const token = getToken()
  // 如果token存在则全部都可以通过
  if (token) {
    next()
    // 网络优化
    if (!store.state.user.userProfile.id) { // 1.调用action函数获取用户数据
      const perms = await store.dispatch('user/getUserProfile')
      // 2.将后端返回的权限数据格式化成我们的权限数据
      console.log('当前权限为:', perms)
      const firstPerms = getFirstRoutePerms(perms)
      console.log(firstPerms)
      const secondPerms = getSecondRoutePerms(perms)
      console.log(secondPerms)
      // 3.权限表示 过滤赛选动态路由
      const routes = getRoutes(firstPerms, secondPerms, asnycRoutes)
      console.log(routes)
      // 4.把动态路由表加入到路由系统中
      routes.forEach(route => {
        router.addRoute(route)
      })
      // 5.调用mutations函数把路由表添加到vuex中
      store.commit('menu/setMenuList', routes)
    }
  } else {
    // 如果在白名单里则通过
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
})
